import { Menu, Icon } from 'ant-design-vue'
import ProIcon from '@/components/Icon/icon.vue'

export default {
  name: 'ProHeaderMenu',
  props: {
    data: {
      type: Array,
      default: () => []
    },
    selectedKey: String
  },
  computed: {
    reSelectedKeys: {
      set(keys) {
        const key = keys && keys.length ? keys[0] : ''
        this.$emit('select', key)
        this.$emit('update:selectedKey', key)
      },
      get() {
        return this.selectedKey ? [ this.selectedKey ] : []
      }
    },
    rootMenu() {
      return this.data.map(d => {
        const ret = { ...d }
        delete ret.children
        return ret
      })
    }
  },
  methods: {
    handleOpen({ key }) {
      this.reSelectedKeys = [ key ]
    }
  },
  render() {
    const renderInner = item => {
      const { meta } = item
      const vnodes = []
      let icon = meta?.icon
      if (icon) {
        const isCustomIcon = icon.startsWith('#')
        icon = isCustomIcon ? icon.slice(1) : icon
        vnodes.push(isCustomIcon ? <ProIcon type={ icon } /> : <Icon type={ icon }/>)
      }
      vnodes.push(<span>{ meta?.title ?? '' }</span>)
      return vnodes
    }
    const renderItem = data => {
      return data.filter(r => !r.hidden).map(item => {
        return item.children && item.children.length
          ? (
            <Menu.SubMenu key={ item.path } scopedSlots={ { title: () => renderInner(item) }}>
              { renderItem(item.children) }
            </Menu.SubMenu>
          )
          : <Menu.Item key={ item.path }>{ renderInner(item) }</Menu.Item>
      })
    }

    const menuProps = {
      props: {
        mode: 'horizontal',
        theme: 'dark',
        selectedKeys: this.reSelectedKeys
      },
      on: {
        click: item => this.handleOpen(item),
        'update:selectedKeys': value => { this.reSelectedKeys = value }
      }
    }

    return <div><Menu { ...menuProps }>{ renderItem(this.rootMenu) }</Menu></div>
  }
}
